package com.ymsoft.myerp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ymsoft.myerp.entity.User;
import com.ymsoft.myerp.mapper.UserMapper;
import com.ymsoft.myerp.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ymsoft.myerp.util.JwtUtils;
import com.ymsoft.myerp.util.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ymsoft
 * @since 2020-04-12
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Resource
    private JwtUtils jwtUtils;

    /**
     * 通过请求获取token，然后获取用户信息
     *
     * @param request
     * @return
     */
    @Override
    public User getUserByToken(HttpServletRequest request, String... token) {
        final String token_start = "Bearer ";
        String auth_token = "";
        if(token != null && token.length > 0) {
            auth_token = token[0];
        } else {
            auth_token = request.getHeader(tokenHeader);
        }
        if (StringUtils.isNotBlank(auth_token)) {
            if (StringUtils.isNotBlank(auth_token) && auth_token.startsWith(token_start)) {
                auth_token = auth_token.substring(token_start.length());
                String username = jwtUtils.getUsernameFromToken(auth_token);
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("username", username);
                return getOne(queryWrapper);
            }
        }
        return null;
    }

    @Override
    public String getUsernameByRequest(HttpServletRequest request) {
        final String token_start = "Bearer ";
        String token = request.getHeader(tokenHeader);
        if (StringUtils.isNotBlank(token)) {
            if (StringUtils.isNotBlank(token) && token.startsWith(token_start)) {
                token = token.substring(token_start.length());
                return jwtUtils.getUsernameFromToken(token);
            }
        }
        return null;
    }
}
